import {
  ArgumentsHost,
  ExceptionFilter,
  HttpException,
  HttpStatus,
} from "@nestjs/common";
import { Response } from "express";

/**
 *
 * 过滤器处理类型为HttpException的异常 及其子类的异常
 * 当异常未识别(既不是HttpException 也不是继承自HttpException的类),
 * 内置的异常过滤器会生成以下默认的JSON相应
 *  {"statusCode":500,"message":"Internal Server Error"}
 */

export class GlobalHttpExceptionFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    if (response.headersSent) {
      return;
    }
    if (exception instanceof HttpException) {
      if (typeof exception.getResponse() === "string") {
        const status = exception.getStatus();
        response.status(status).json({
          statusCode: status,
          message: exception.getResponse(),
        });
      } else {
        response.status(exception.getStatus()).json(exception.getResponse());
      }
    } else {
      return response.status(500).json({
        statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
        error: exception.message,
        message: "Internal Server Error",
      });
    }
  }
}
